#include "tcp_connection.h"
#include <iostream>

namespace rr {
namespace nio {

TcpConnection::TcpConnection(EventLoop::Sptr loop, boost::asio::ip::tcp::socket& socket)
: loop_(loop)
, socket_(std::move(socket))
{
    read_buf_.resize(64*1024);
    printf("TcpConnection::TcpConnection() this[%p]\n", this);
}

TcpConnection::~TcpConnection()
{
    printf("TcpConnection::~TcpConnection() this[%p]\n", this);
}

void TcpConnection::SetConnectSuccess()
{
    if(connection_cb_) {
        connection_cb_(shared_from_this());
    }

    DoRead();
}

int32_t TcpConnection::DoClose()
{
    try
    {
        socket_.close();
    }
    catch(const std::exception& e)
    {
        printf("TcpConnection::DoClose error: %s\n", e.what());
        return -1;
    }
    
    return 0;
}

void TcpConnection::DoRead()
{
    auto self = shared_from_this();
    auto async_read_func = [this, self](boost::system::error_code ec, std::size_t length) {
        if(ec) {
            std::cout << "TcpConnection::DoRead ec msg=" << ec.message() << " tid=" << std::this_thread::get_id() << std::endl;
            OnClose();
            return;
        }
        std::cout << "TcpConnection::DoRead length:=" << length << " msg:" << read_buf_.data() << " tid=" << std::this_thread::get_id() << std::endl;
        //HandleRead(length);
        DoRead();
    };

    socket_.async_read_some(boost::asio::buffer(read_buf_.data(), read_buf_.size()), async_read_func);

    return;
}

void TcpConnection::OnClose()
{
    if(close_cb_) {
        close_cb_(shared_from_this());
    }
}

} //namespace 
} //namespace 